<template>
  <el-container style="padding:10px;">
    <el-aside style="float: left;width: 300px;">
      <!-- 头部操作按钮 -->
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <el-button class="el-button-pad" type="primary" icon="el-icon-plus" size="small" @click="newModal">新增</el-button>
          <el-input v-model="searchValue" size="small" placeholder="请搜索..." suffix-icon="el-icon-search" @click="searchShow" style="width: 194px;margin-left: 5px; display: inline-block"></el-input>
        </div>
        <div slot="header" class="clearfix">
          <!-- <el-button class="el-button-pad" size="small" @click="newModal">新增同级</el-button> -->
          <!-- <el-button class="el-button-pad" size="small" @click="newModal">新增</el-button> -->
          <!-- <el-button class="el-button-pad" size="small" @click="searchShow">查询</el-button> -->
          <!-- <el-button class="el-button-pad" type="primary" icon="el-icon-plus" size="small" @click="newModal">新增</el-button> -->
          <!-- <el-button class="el-button-pad" type="primary" icon="el-icon-search" size="small" @click="searchShow">搜索</el-button> -->
        </div>
        <div class="text item el-over-auto">
          <!-- Tree 树形控件 -->
          <el-tree
            :data="data"
            :key="treeKey"
            :default-expanded-keys="defaultArrId"
            :props="defaultProps"
            node-key="dictTypeId"
            @node-click="handleNodeClick"
            ref="orgTree"
            :filter-node-method="filterNode"
            :load="loadNode1"
            lazy>
              <!-- <span class="custom-tree-node" slot-scope="{ node }">{{ node.label }}</span> -->
          </el-tree>
        </div>
      </el-card>
    </el-aside>
    <el-main style="padding: 0px 0px 0px 10px;">
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <span><i class="el-icon-warning-outline"></i> 值集信息</span>
          <div style="float: right">
            <el-button v-if="showBtn" type="primary" icon="el-icon-edit" size="small" @click="amend">修改</el-button>
            <el-button v-else type="primary" icon="el-icon-circle-check" size="small" @click="btnSave">保存</el-button>
            <el-button type="primary" icon="el-icon-delete" size="small" @click="removeTree()">删除</el-button>
          </div>
        </div>
        <!-- 表格 -->
        <div class="text item">
          <el-form label-width="80px" class="el-flex-none" size="small">
            <el-form-item label="编码:">
              <el-col :span="12">
                <el-input v-model="formObj.dictTypeId" readonly></el-input>
              </el-col>
               <!-- <el-button
                style=" margin-left: 10px"
                type="text"
                icon="el-icon-edit"
                @click="amend"
                size="small"
                v-if="showBtn"
              >修改</el-button>
              <el-button
                style=" margin-left: 10px"
                type="text"
                icon="el-icon-edit"
                @click="btnSave"
                size="small"
                v-else
              >保存</el-button> -->
            </el-form-item>
            <el-form-item label="名称:">
              <el-col :span="12">
                <el-input v-model="formObj.dictTypeName" :readonly="readonly"></el-input>
              </el-col>
            </el-form-item>
            <!-- <el-form-item label="上级类型:">
              <el-col :span="12">
                <el-input readonly></el-input>
              </el-col>
            </el-form-item> -->
            <!-- <el-form-item label="说明:">
              <el-col :span="12">
                <el-input v-model="formObj.dictTypeName" readonly></el-input>
              </el-col>
            </el-form-item> -->
            <!-- <el-form-item label="排序号:">
              <el-col :span="12">
                <el-input v-model="formObj.seqNo" readonly></el-input>
              </el-col>
            </el-form-item> -->
          </el-form>
          <div style="text-align:right;">
            <!-- <el-button
              type="text"
              icon="el-icon-plus"
              @click="addRows"
            >新增</el-button> -->
          </div>
          <div class="el-flex el-box-column">
            <!-- <el-table
            :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            border
            height="100%">
            <el-table-column type="selection"></el-table-column>
            <el-table-column
              prop="id"
              label="序号"
              align="center"
              sortable
              width="80"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="dictTypeId" label="编码" align="center" width="140" show-overflow-tooltip></el-table-column>
            <el-table-column prop="dictTypeName" label="名称" align="center" min-width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="expanded" label="说明" align="center" min-width="300" show-overflow-tooltip></el-table-column>
            <el-table-column prop="operate" label="操作" align="center" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.$index, scope.row)"
                  circle
                ></el-button>
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.$index, scope.row)"
                  circle
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" align="center" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-top"
                  @click="handleUp(scope.$index, scope.row)"
                  circle
                ></el-button>
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-bottom"
                  @click="handleDown(scope.$index, scope.row)"
                  circle
                ></el-button>
              </template>
            </el-table-column>
          </el-table> -->
          </div>
       <!-- 分页 -->
          <!-- <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
          ></el-pagination> -->
        </div>
      </el-card>
        <!-- 编辑弹框 -->
        <!-- <el-dialog title="编辑" :visible.sync="dialogVisible" :before-close="handleClose">
          <el-form>
            <el-form-item label="编码">
              <el-input v-model="addTabelData.coding" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="名称">
              <el-input v-model="addTabelData.name" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="说明">
              <el-input v-model="addTabelData.explain" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleCheck">确 定</el-button>
          </span>
        </el-dialog> -->
        <!-- 模态框 -->
      <el-dialog title="值集信息" :visible.sync="dialogFormVisible" :close-on-click-modal = false :close-on-press-escape = false :before-close="handleClose">
        <el-form :model="orgForm" label-width="80px" size="small" :rules="rules" ref="orgForm">
          <el-form-item
            label="编码"
            prop="dictTypeId"
            :rules="[
              {
                required: true,
                message: '编码不能为空'
              }
            ]"
            >
            <el-col :span="12"><el-input placeholder="请输入编码" v-model="orgForm.dictTypeId" autocomplete="off"></el-input></el-col>
          </el-form-item>
          <el-form-item
            label="名称"
            prop="dictTypeName"
            :rules="[
              {
                required: true,
                message: '名称不能为空'
              }
            ]"
            >
            <el-col :span="15"><el-input placeholder="请输入名称" v-model="orgForm.dictTypeName" autocomplete="off"></el-input></el-col>
          </el-form-item>
          <el-form-item label="上级类型">
            <el-col :span="15">
              <el-input v-model="orgForm.parentName" placeholder="请输入上级类型" autocomplete="off" readonly><el-button slot="append" icon="el-icon-search" @click="dialogClick"></el-button></el-input>
              <el-input type="hidden" v-model="orgForm.parentId"></el-input>
            </el-col>
          </el-form-item>
          <!-- <el-form-item label="说明" prop="explain">
            <el-col :span="9"><el-input placeholder="请输入说明" v-model="orgForm.explain" autocomplete="off"></el-input></el-col>
          </el-form-item>
          <el-form-item label="是否启用"><el-switch v-model="orgForm.enableFlag"></el-switch></el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确定</el-button> -->
          <el-button @click="handleCheckClose()">取 消</el-button>
          <el-button type="primary" @click="handleCheckSure">确 定</el-button>
        </div>
      </el-dialog>
      <elDialog @dialogHide="dialogHanderHide" :dialogVisible="isShow"></elDialog>
    </el-main>
  </el-container>
</template>
<script>
// import { list } from '@/api/eosDictType'
// import axios from 'axios'
import { Tree, Dialog, Table, TableColumn, Pagination, MessageBox, Message } from 'element-ui'
import elDialog from '../../../components/dialog'
export default {
  name: 'wordbook',
  components: {
    'el-tree': Tree, // 树形菜单
    'el-dialog': Dialog, // 对话框
    'el-table': Table, // 表格
    'el-table-column': TableColumn, // 表格列
    'el-pagination': Pagination, // 分页
    elDialog
  },
  data () {
    // var validateDictTypeId = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入编码'))
    //   } else {
    //     if (this.ruleForm.dictTypeId !== '') {
    //       this.$refs.ruleForm.validateField('dictTypeId')
    //     }
    //     callback()
    //   }
    // }
    // var validateDictTypeName = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入名称'))
    //   } else {
    //     if (this.ruleForm.dictTypeName !== '') {
    //       this.$refs.ruleForm.validateField('dictTypeName')
    //     }
    //     callback()
    //   }
    // }
    return {
      isShow: false,
      inpDialog: false,
      readonly: true, // input框是否只读
      currentPage: 1, // 前往去的页
      pagesize: 10,
      data: [], // 侧边栏数据
      defaultProps: {
        label: 'dictTypeName',
        isLeaf: 'isLeaf'
      },
      treeKey: 1,
      addTabelData: {
        // 新增空数组
        coding: '',
        name: ''
      },
      orgForm: {},
      search: false,
      showBtn: true,
      searchValue: '',
      dialogVisible: false, // 弹框是否显示
      dialogFormVisible: false, // 模态框隐藏
      formObj: {},
      tabelObj: {},
      rules: {
        // dictTypeId: [
        //   { validator: validateDictTypeId, trigger: 'blur' }
        // ],
        // dictTypeName: [
        //   { validator: validateDictTypeName, trigger: 'blur' }
        // ]
      },
      delId: '',
      editName: '',
      nowDictTypeId: '',
      tableData: [], // 表格数据
      defaultArrId: [], //  点击tree选中存下dictTypeid
      typeid: '', // 从子集获取过来的dictTypeId
      parentName: '', // 从子集获取过来的dictName
      dictParentId: '',
      ruleForm: {
        dictTypeId: '',
        dictTypeName: ''
      },
      obj: {} // 存放节点的id对象
    }
  },
  watch: {
    searchValue (val) {
      this.$refs.orgTree.filter(val)
    }
  },
  // mounted () {
  //   list({'page': 1, 'size': 10}).then(data => {
  //     console.log('成功', data)
  //   }).catch(err => {
  //     console.log('失败', err)
  //   })
  // },
  created () {
    // this.tabelList()
  },
  methods: {
    // tabelList () {
    //   this.axios.post('/eosDictType/list', {dictTypeId: this.delId}).then(res => {
    //     this.data = res.data.data
    //     console.log(this.data)
    //   }).catch(error => {
    //     console.log(error, '失败')
    //   })
    // },
    dialogClick () {
      this.isShow = true
    },
    dialogHanderHide (result) {
      console.log(result)
      this.isShow = false
      // result === false(点击了取消)  result === true(点击了确定)
      // if (result) console.log('点击了确定', result)
      if (!result) return console.log('点击了取消', result)
      this.orgForm.parentId = result.dictTypeId
      this.orgForm.parentName = result.dictTypeName
      // this.obj = { // 存放节点的dictTypeId
      //   isTop: result.parentId,
      //   dictTypeId: result.dictTypeId
      // }
    },
    removeTree () {
      MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delData()
        })
        .catch(() => {})
    },
    delData () {
      this.axios.post('/eosDictType/del', [{dictTypeId: this.delId}]).then(res => {
        // console.log(res)
        this.treeKey += 1
      }).catch(error => {
        console.log(error)
      })
    },
    newModal () {
      this.dialogFormVisible = true
    },
    // 搜索框显示
    searchShow () {
      // this.search = true
      this.searchValue = ''
    },
    // 搜索框隐藏
    // searchHide () {
    //   this.search = false
    // },
    loadNode1 (node, resolve) {
      node.data && this.toJudge(node.data)
      console.log(node.data)
      if (node.level === 0) {
        this.axios.post('/eosDictType/list').then(res => {
          let parentData = []
          res.data.data.forEach(e => {
            parentData.push(e)
          })
          parentData.forEach(item => {
            this.defaultArrId = [ parentData[0].dictTypeId ]
            console.log(item.dictTypeId)
          })
          console.log(parentData)
          resolve(parentData)
        }).catch(res => {
          resolve([])
        })
      } else {
        // console.log(' 当前节点id值为：' + node.data.dictTypeId)
        let id = node.data.dictTypeId
        this.axios.get(`/eosDictType/children/${id}`).then(res => {
          let childrenList = []
          res.data.data.forEach(e => {
            childrenList.push(e)
          })
          resolve(childrenList)
        }).catch(res => {
          resolve([])
        })
      }
    },
    // 点击侧边栏触发事件
    handleNodeClick (nodeObj, node) {
      // this.defaultArrId = this.node.data.dictTypeId
      console.log(node)
      this.toJudge(nodeObj)
    },
    // 判断选中的发生了变化
    toJudge (nodeObj) {
      if (this.nowDictTypeId === nodeObj.dictTypeId) return false
      else {
        this.nowDictTypeId = nodeObj.dictTypeId
        this.delId = nodeObj.dictTypeId
        this.editName = nodeObj.dictTypeName
        // if (nodeObj.rank === 1) { // 点击的是父级别的节点
        let tempObj = {
          dictTypeId: nodeObj.dictTypeId,
          dictTypeName: nodeObj.dictTypeName,
          seqNo: nodeObj.seqNo
        }
        console.log(tempObj)
        this.formObj = tempObj
        this.axios.post('/eosDictType/list', {dictTypeId: this.delId}).then(res => {
          this.tableData = res.data.data
          console.log(this.tableData)
        }).catch(error => {
          console.log(error, '失败')
        })
        // }
        // else { // 点击的是子级别的节点
        // let childrenObj = {
        //   dictTypeId: nodeObj.dictTypeId,
        //   dictTypeName: nodeObj.dictTypeName,
        //   expanded: nodeObj.expanded
        // }
        // this.tabelObj = childrenObj
        // }
      }
    },
    // 树菜单检索方法
    filterNode (value, data) {
      console.log(data)
      // this.axios.post('/eosDictType/dictTypeSearch', {dictTypeId: data.dictTypeId, dictTypeName: data.dictTypeName}).then(res => {
      if (!value) return true
      return data.dictTypeName.indexOf(value) !== -1
      // })
    },
    // 修改事件
    amend () {
      this.readonly = !this.readonly
      this.showBtn = false
    },
    // 保存事件
    btnSave () {
      this.axios.post('/eosDictType/up', {dictTypeId: this.delId, dictTypeName: this.formObj.dictTypeName}).then(res => {
        // console.log(res.data.code)
        this.readonly = !this.readonly
        this.treeKey += 1
      }).catch(error => {
        console.log(error, '失败')
      })
      this.showBtn = true
    },
    // 新增事件
    addRows () {
      this.axios.post('/eosDictEntry/sv', {
        'dictTypeId': this.delId,
        'dictId': this.tableData.dictTypeId,
        'dictName': this.tableData.dictTypeName,
        'sortNo': '1'}).then(res => {
        console.log(res)
      }).catch(error => {
        console.log(error, '失败')
      })
      // var addTabelData = Object.assign({}, this.addTabelData) // 将addTabelData克隆一份到{}里
      // this.tableData.push(addTabelData)
    },
    // 单行编辑
    handleEdit (index, row) {
      this.addTabelData = row
      this.dialogVisible = true
    },
    // 编辑弹框确认
    handleCheck () {
      this.tableData[this.index] = this.addTabelData
      this.dialogVisible = false
    },
    // 弹框确认
    handleCheckSure () {
      // console.log('111')
      this.$refs.orgForm.validate((valid) => {
        if (valid) {
          if (this.orgForm.parentId) {
            this.axios.post('/eosDict/next', this.orgForm).then(res => {
              console.log(res)
              if (res.data.code === 10000) {
                this.dialogFormVisible = false
                this.treeKey += 1
              }
              this.handleCheckClose()
            })
            this.dialogFormVisible = false
          } else {
            this.axios.post('/eosDict/svOrUp', this.orgForm).then(res => {
              console.log(res)
              if (res.data.code === 10000) {
                this.dialogFormVisible = false
                this.treeKey += 1
              }
              this.handleCheckClose()
            })
          }
        } else {
          return false
        }
      })
      // if (!this.dictParentId) {
      // if (this.orgForm.parentId) {
      //   this.axios.post('/eosDictType/next', this.orgForm).then(res => {
      //     console.log(res)
      //     if (res.data.code === 10000) {
      //       this.dialogFormVisible = false
      //       this.treeKey += 1
      //     }
      //     this.handleCheckClose()
      //   })
      //   this.dialogFormVisible = false
      // } else {
      //   this.axios.post('/eosDictType/sv', this.orgForm).then(res => {
      //     console.log(res)
      //     if (res.data.code === 10000) {
      //       this.dialogFormVisible = false
      //       this.treeKey += 1
      //     }
      //     this.handleCheckClose()
      //   })
      // }
    },
    handleCheckClose () {
      this.$refs.orgForm.resetFields()
      this.orgForm = {}
      this.dialogFormVisible = false
    },
    close () {
      this.$refs.orgForm.resetFields()
      this.orgForm = {}
      this.dialogFormVisible = false
    },
    // 编辑弹框关闭提示框
    handleClose () {
      MessageBox.confirm('确认关闭值集信息弹框吗？')
        .then(_ => {
          this.handleCheckClose()
        })
        .catch(_ => {})
    },
    // 删除tabel行
    handleDelete (index, row) {
      MessageBox.confirm('您是否确定删除选中内容', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // this.tableData.splice(index, 1)
          // Message({
          //   type: 'success',
          //   message: '删除成功!'
          // })
          this.delRowData()
        })
        .catch(() => {
          // Message({
          //   type: 'info',
          //   message: '已取消删除'
          // })
        })
    },
    delRowData () {
      this.axios.post('/eosDictEntry/del', [{dictId: this.delId, seqNo: 'seqNo'}]).then(res => {
        console.log(res)
      }).catch(error => {
        console.log(error)
      })
    },
    // 向上移动
    handleUp (index, row) {
      var that = this
      if (index > 0) {
        var upDate = that.tableData[index - 1]
        that.$set(that.tableData, index - 1, that.tableData[index])
        that.$set(that.tableData, index, upDate)
      } else {
        Message({
          showClose: true,
          message: '已经是第一条了，不可以上移',
          type: 'warning'
        })
      }
    },
    // 向下移动
    handleDown (index, row) {
      var that = this
      if (index + 1 === that.tableData.length) {
        Message({
          showClose: true,
          message: '已经最后一条了，不可以下移',
          type: 'warning'
        })
      } else {
        let downDate = that.tableData[index + 1]
        that.tableData.splice(index + 1, 1)
        that.tableData.splice(index, 0, downDate)
      }
    },
    // 每页展示条数
    handleSizeChange (val) {
      this.pagesize = val
    },
    // 当前页
    handleCurrentChange (val) {
      this.currentPage = val
    }
  }
}
</script>
<style lang="scss">
// .el-button.el-button-pad {
//   padding-left: 8px;
//   padding-right: 8px;
//   float: right;
// }
// .el-button.el-button-pad + .el-button.el-button-pad {
//   margin-left: 7px;
// }
.el-table{
  th{
    padding: 6px 0;
  }
  td{
    padding: 6px 0;
  }
}
</style>
